package com.woniuxy.commons.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.model.Result;
import com.woniuxy.service.MenuInfoService;
import com.woniuxy.service.dto.MenuDto;
import com.woniuxy.service.dto.UserDetailsDto;
import com.woniuxy.service.dto.UserLoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Service
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private ObjectMapper om = new ObjectMapper();

    @Autowired
    private MenuInfoService menuInfoService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        response.setCharacterEncoding("utf8");
        response.setContentType("application/json;charset=utf8");

        UserLoginDto uld = new UserLoginDto();
        UserDetailsDto ud = (UserDetailsDto)authentication.getPrincipal();

        uld.setAccountId(ud.getAccountId());
        uld.setId(ud.getId());
        uld.setUsername(ud.getUsername());
        uld.setPhone(ud.getPhone());
        //查询出对应的菜单集合
        List<MenuDto> menuDtos = menuInfoService.loadMenuByAccount(ud.getAccountId());

        uld.setMenus(menuDtos);

        Result result = Result.success(200,"登录成功",uld);
        String json = om.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }

}
